<template>

  <!-- 聊天空间 -->
  <ul v-if="currentUser != null && userIdMapUser != null && msgData.length > 0" v-infinite-scroll="load"
      class="infinite-list" style="overflow: auto">
    <li v-for="msg in msgData">

      <!-- 好友 -->
      <div v-if="msg.fromUid !== currentUser.id" class="infinite-list-item-other">
        <el-avatar
            style="height: 30px;width: 30px"
            :src="userIdMapUser[msg.fromUid]?.avatarUrl"
        />
        <div style="margin-left: 4px">
          <div style="height: 35%;font-size: 10px;margin-left: 4px;">
            {{userIdMapUser[msg.fromUid]?.username}}
          </div>

          <!-- 文本消息 -->
          <div v-if="1 == msg.type" style="font-size: 14px;background-color: #ffffff;border-radius: 5px;padding: 2px;">{{msg.content}}</div>

          <!-- 表情包 -->
          <div v-else-if="2 == msg.type" style="display: flex;justify-items: center">
            <van-image style="height: 32px;width: 32px;"
                       :src="msg.content"
            />
          </div>


          <!-- 邀请加入队伍的链接 -->
          <div v-else-if="4 == msg.type" style="display: flex;justify-items: center;background-color: #ffffff;border-radius: 5px">
            <!-- 跳转点击弹出加入队伍的浮窗 -->
            <div @click="showInviteTeamDialogMethod(msg.content)">
              <div style="display: flex;">
                <van-image :src="msg.content.imageUrl" width="45px" height="45px" fit="cover" style="margin-left: 6px;margin-top: 6px"/>
                <div style="margin-left: 6px;margin-right: 6px">
                  <div style="font-size: 14px;">邀请你加入队伍</div>
                  <van-text-ellipsis
                      style="width: 130px;font-size: 12px;color: #333333"
                      rows="3"
                      :content="'\'\''+ userIdMapUser[msg.fromUid]?.username + '\'\'' + '邀请你加入队伍'+ '\'\'' + msg.content.teamName + '\'\''"
                  />

                </div>
              </div>
              <div v-if="msg.content.password != null && msg.content.password.length > 0" style="margin-top: 6px;text-align: center;">
                <span>邀请码: {{msg.content.password}}</span>
              </div>

            </div>
          </div>
        </div>
      </div>

      <!-- 自己 -->
      <div v-else class="infinite-list-item-me">
        <div>
          <!-- 文本消息 -->
          <div v-if="1 == msg.type" style="margin-right: 4px;font-size: 14px;background-color: #d4f5a7;border-radius: 5px;padding: 2px;">{{msg.content}}</div>
          <!-- 表情包 -->
          <div v-else-if="2 == msg.type" style="display: flex;justify-items: center">
            <van-image style="height: 32px;width: 32px;margin-right: 4px;"
                       :src="msg.content"
            />
          </div>

          <!-- 邀请加入队伍的链接 -->
          <div v-else-if="4 == msg.type" style="margin-right:6px;display: flex;justify-items: center;background-color: #d4f5a7;border-radius: 5px">
            <!-- 跳转点击弹出加入队伍的浮窗 -->
            <div>
              <div style="display: flex;">
                <van-image :src="msg.content.imageUrl" width="45px" height="45px  " fit="cover" style="margin-left: 6px;margin-top: 6px"/>
                <div style="margin-left: 6px;margin-right: 6px">
                  <div style="font-size: 14px;">邀请你加入队伍</div>
                  <van-text-ellipsis
                      style="width: 130px;font-size: 12px;color: #333333"
                      rows="3"
                      :content="'\'\''+ currentUser.username + '\'\'' + '邀请你加入队伍'+ '\'\'' + msg.content.teamName + '\'\''"
                  />

                </div>
              </div>
              <div v-if="msg.content.password != null && msg.content.password.length > 0" style="margin-top: 6px;text-align: center;">
                <span>邀请码: {{msg.content.password}}</span>
              </div>
            </div>
          </div>

        </div>

        <el-avatar
            style="height: 30px;width: 30px"
            :src="currentUser.avatarUrl"
        />
      </div>

    </li>
  </ul>

  <!-- 输入 -->
  <div class="chatInputDiv">
    <van-image style="height: 30px;width: 30px;margin-right: 6px"
               src="http://120.26.146.100:8889/public/sound.png"/>
    <el-input
        v-model="meMsgIn"
        style="width: 68%"
        autosize
        type="textarea"
        placeholder=""
    />

    <van-popover v-model:show="showPopover" placement="top-end" style="width: 88%">
      <van-grid
          square
          clickable
          :border="false"
          column-num="9"
          style="width: 100%;margin-bottom: 4px;margin-top: 2px;"
      >
        <van-grid-item
            style="width: 20px;height: 20px;margin-left: 4px"
            v-for="emoji in imageEmojiList"
            :key="emoji.name"
            :icon="emoji.imageUrl"
            @click="sendEmoji(emoji.id)"
        />
      </van-grid>
      <template #reference>
        <van-button style="width: 0;height: 0;margin-left: 5px;margin-bottom: 14px">
          <template #icon>
            <van-image style="height: 38px;width: 38px;margin-right: 2px"
                       src="http://120.26.146.100:8889/public/emoji.png"
            />
          </template>
        </van-button>
      </template>
    </van-popover>

    <van-image
        class="sendIcon"
        style="height: 28px;width: 28px;margin-left: 2px"
        src="http://120.26.146.100:8889/public/send.png"
        @click="sendUserMsg"
        :style="{ transform: `rotate(${rotationAngle}deg)` }"
    />


    <!--弹框的内容-->
    <van-dialog :close-on-click-overlay="true"
                @cancel="showAddTeamDialog = false"
                @confirm="addTeam(currentUser.id, chatTeamAddNet)"
                v-model:show="showAddTeamDialog" title="加入队伍"
                confirm-button-text="加入" cancel-button-text="取消"
                show-cancel-button>
      <div style="display: flex;justify-content: center;align-items: center;margin-top: 10px;margin-bottom: 10px">
        <van-image :src="chatTeamAddNet.imageUrl" width="60px" height="60px" fit="cover"/>
        <span style="margin-left: 10px;text-align: center;font-size: 16px;font-weight: bold">{{chatTeamAddNet?.teamName}}</span>
      </div>
      <van-password-input
          v-if="chatTeamAddNet.password != null  && chatTeamAddNet.password.length > 0"
          :value="chatTeamAddNet.password"
          :length="6"
      />
      <van-password-input
          v-else
          value="123456"
          :length="6"
      />
    </van-dialog>


    <van-dialog v-model:show="showDialog">
      <div>sssss</div>
    </van-dialog>

  </div>

</template>

<script setup lang="ts">

import { onMounted, ref} from "vue";
import {userStore} from "../stores/user/user.ts";
import {chatStore} from "../stores/chat/chat.ts";
import {getChatFriendMessageByKey, getChatTeamMessageByTeamId} from "../api/chatApi.ts";
import {showToast} from "vant";
import {
  connectionSendFriendChat, connectionSendFriendChatEmoji,
  connectionSendTeamChat,
  connectionSendTeamChatEmoji,
  onIsConnect
} from "../ws/socketWork.ts";
import {joinTeamInvite} from "../api/teamApi.ts";


//获取路由跳转传过来的数据
const chatStoreAPI = chatStore();


const userStoreAPI = userStore();//存储pina=>用户
const meMsgIn = ref('');//发送新的消息
const currentUser = ref();//当前用户信息
const friendUser = ref();//好友用户信息
const chatData = ref();//聊天室的一些基本信息(聊天室的类型、用户信息等等)
const userIdMapUser = ref();//存储用户id->user的数据，方便消息拿到能快速根据id拿到数据然后push到msgData
const chatMsgNet = ref();//别人发的消息
const chatTeamAddNet = ref();//别人邀请加入队伍的消息

//消息总信息
const msgData = ref([
  {
    fromUid: 7,
    avatarUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    username: '张三',
    content: '你们最近怎么样啦'
  },
  {
    fromUid: 8,
    avatarUrl: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    username: '李四',
    content: '我还行'
  },
]);
const i = ref(5);

const showAddTeamDialog = ref(false);
const showDialog = ref(false);

//加载更多消息
const load = () => {
  // i.value = i.value + 1;
  // const msg =   {
  //   id: i.value,
  //   avatarUrl: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
  //   username: "电玩小子",
  //   content: '我也还行'
  // };
  // msgData.value.push(msg);
}

//本地图片/本地表情包
const imageEmojiList = [
  {imageUrl:'http://120.26.146.100:8889/emoji/1.png', name:'酷拽', id:1},
  {imageUrl:'http://120.26.146.100:8889/emoji/2.png', name:'哭', id:2},
  {imageUrl: 'http://120.26.146.100:8889/emoji/3.png', name:'微笑', id:3,},
  {imageUrl: 'http://120.26.146.100:8889/emoji/4.png', name:'害怕', id:4},
  {imageUrl: 'http://120.26.146.100:8889/emoji/5.png', name:'喜欢', id:5},
  {imageUrl: 'http://120.26.146.100:8889/emoji/6.png', name:'惊呆', id:6},
  {imageUrl: 'http://120.26.146.100:8889/emoji/7.png', name:'害羞', id:7},
  {imageUrl: 'http://120.26.146.100:8889/emoji/8.png', name:'闭嘴', id:8},
  {imageUrl: 'http://120.26.146.100:8889/emoji/9.png', name:'晚安', id:9},
  {imageUrl: 'http://120.26.146.100:8889/emoji/10.png', name:'生气', id:10},
  {imageUrl: 'http://120.26.146.100:8889/emoji/11.png', name:'开心', id:11},
  {imageUrl: 'http://120.26.146.100:8889/emoji/12.png', name:'惊讶', id:12},
  {imageUrl: 'http://120.26.146.100:8889/emoji/13.png', name:'不嘻嘻', id:13},
  {imageUrl: 'http://120.26.146.100:8889/emoji/14.png', name:'笑死', id:14},
  {imageUrl: 'http://120.26.146.100:8889/emoji/15.png', name:'啊', id:15},
  {imageUrl: 'http://120.26.146.100:8889/emoji/16.png', name:'嘻嘻', id:16},
  {imageUrl: 'http://120.26.146.100:8889/emoji/17.png', name:'白眼', id:17},
  {imageUrl: 'http://120.26.146.100:8889/emoji/18.png', name:'傲慢', id:18},
  {imageUrl: 'http://120.26.146.100:8889/emoji/19.png', name:'困', id:19},
  {imageUrl: 'http://120.26.146.100:8889/emoji/20.png', name:'嘿哈', id:20},
  {imageUrl: 'http://120.26.146.100:8889/emoji/21.png', name:'疑问', id:21},
  {imageUrl: 'http://120.26.146.100:8889/emoji/22.png', name:'嘘', id:22},
  {imageUrl: 'http://120.26.146.100:8889/emoji/23.png', name:'委屈', id:23},
  {imageUrl: 'http://120.26.146.100:8889/emoji/24.png', name:'快哭了', id:24},
  {imageUrl: 'http://120.26.146.100:8889/emoji/25.png', name:'阴险', id:25},
  {imageUrl: 'http://120.26.146.100:8889/emoji/26.png', name:'亲亲', id:26},
  {imageUrl: 'http://120.26.146.100:8889/emoji/27.png', name:'可怜', id:27},
  {imageUrl: 'http://120.26.146.100:8889/emoji/28.png', name:'捂脸', id:28},
  {imageUrl: 'http://120.26.146.100:8889/emoji/29.png', name:'机智', id:29},
  {imageUrl: 'http://120.26.146.100:8889/emoji/30.png', name:'吃瓜', id:30},
  {imageUrl: 'http://120.26.146.100:8889/emoji/31.png', name:'狗头', id:31},
  {imageUrl: 'http://120.26.146.100:8889/emoji/32.png', name:'裂开', id:32},
  {imageUrl: 'http://120.26.146.100:8889/emoji/33.png', name:'哇', id:33},
  {imageUrl: 'http://120.26.146.100:8889/emoji/34.png', name:'让我看看', id:34},
  {imageUrl: 'http://120.26.146.100:8889/emoji/36.png', name:'666', id:35},
  {imageUrl: 'http://120.26.146.100:8889/emoji/36.png', name:'加油', id:36},
  {imageUrl: 'http://120.26.146.100:8889/emoji/37.png', name:'叹气', id:37},
  {imageUrl: 'http://120.26.146.100:8889/emoji/38.png', name:'敲打', id:38},
  {imageUrl: 'http://120.26.146.100:8889/emoji/39.png', name:'OK', id:39},
  {imageUrl: 'http://120.26.146.100:8889/emoji/40.png', name:'点赞', id:40},
];


//监听好友申请事件(当使用该页面时)，没有使用直接加载时onMounted查询数据库即可  /
// 监听连接成功事件（自定义） =》 先监听后触发事件(连接成功触发)
window.addEventListener('chat', function(event) {
  console.log('chat');
  chatMsgNet.value = event.detail;
  if (chatMsgNet.value.messageType == 4){//私聊-文本
    // 在这里对获取到的数据进行处理
    const msg = {
      fromUid: chatMsgNet.value.fromUid,
      content: chatMsgNet.value.content,
      createTime: Date.now(),
      type:1
    };
    console.log('chatMsgNet',chatMsgNet.value);
    console.log('msg',msg);
    console.log('curId',currentUser.value.id)
    //本地推送
    msgData.value.push(msg);
  }else if (chatMsgNet.value.messageType == 5){//群聊-文本
    // 在这里对获取到的数据进行处理
    const msg = {
      fromUid: chatMsgNet.value.fromUid,
      content: chatMsgNet.value.content,
      createTime: Date.now(),
      type:1
    };
    //本地推送
    msgData.value.push(msg);
  }else if (chatMsgNet.value.messageType == 6){//单聊-表情包
    // 在这里对获取到的数据进行处理
    const msg = {
      fromUid: chatMsgNet.value.fromUid,
      content: chatMsgNet.value.content,
      createTime: Date.now(),
      type:2
    };
    //本地推送
    msgData.value.push(msg);
  }else if (chatMsgNet.value.messageType == 7){//群聊-表情包
    // 在这里对获取到的数据进行处理
    const msg = {
      fromUid: chatMsgNet.value.fromUid,
      content: chatMsgNet.value.content,
      createTime: Date.now(),
      type:2
    };
    //本地推送
    msgData.value.push(msg);
  }else if (chatMsgNet.value.messageType == 8){// 单聊 - 邀请好友加入队伍的消息
    // content 是一个json字符串
    /*
    "content":{
                "teamId":1,
                "teamName":"队伍名称",
                "imageUrl":"队伍头像",
                "password":"<PASSWORD>"
            }
     */
    const content = JSON.parse(chatMsgNet.value.content);

    const msg = {
      fromUid: chatMsgNet.value.fromUid,
      content: content,
      createTime: Date.now(),
      type:4 ,// 3邀请加入队伍
      show:false,
    };
    //本地推送
    msgData.value.push(msg);
  }


});

const isRotating = ref(false);
const rotationAngle = ref(0);
const showPopover = ref(false);

//发送表情包
const sendEmoji = (id)=>{
  showPopover.value = false;
  let imageEmojiUrl;
  for (let j = 0; j < imageEmojiList.length; j++) {
    if (id == imageEmojiList[j].id) {
      imageEmojiUrl = imageEmojiList[j].imageUrl;
    }
  }
  console.log('imageEmojiUrl',imageEmojiUrl);
  //todo 看看好像是可以去掉avatarUrl的
  const msg = {
    fromUid: currentUser.value.id,
    avatarUrl: currentUser.value.avatarUrl,
    content: imageEmojiUrl,
    createTime: Date.now(),
    type:2,//消息类型，1文本 2表情包
  };
  //本地发送
  msgData.value.push(msg);

  //网络发送给好友/队伍 =》 表情包
  if (chatData.value.type == 0){//chatData.value.id = 队伍id(群发)
    connectionSendTeamChatEmoji(currentUser.value.id,imageEmojiUrl,chatData.value.id);
  }else if (chatData.value.type == 1){//单发
    connectionSendFriendChatEmoji(currentUser.value.id,imageEmojiUrl,friendUser.value.id);
  }

}


//发送信息
const sendUserMsg = ()=>{
  //实现动态发送火箭的旋转
  if (!isRotating.value) {
    isRotating.value = true;
    rotationAngle.value = -100;
    const intervalId = setInterval(() => {
      if (rotationAngle.value < 0) {
        rotationAngle.value = rotationAngle.value + 2;
      } else {
        isRotating.value = false;
        clearInterval(intervalId);
      }
    }, 5);
  }

  if ('' === meMsgIn.value){
    return;
  }

  const msg = {
    fromUid: currentUser.value.id,
    avatarUrl: currentUser.value.avatarUrl,
    content: meMsgIn.value,
    createTime: Date.now(),
    type:1,//消息类型，1文本 2表情包
  };
  //本地发送
  msgData.value.push(msg);

  console.log("chatData",chatData.value);
  //网络发送给好友
  if (chatData.value.type == 0){//chatData.value.id = 队伍id(群发)
    connectionSendTeamChat(currentUser.value.id,meMsgIn.value,chatData.value.id);
  }else if (chatData.value.type == 1){//单发
    connectionSendFriendChat(currentUser.value.id,meMsgIn.value,friendUser.value.id);
  }
  meMsgIn.value = '';

}





//挂载获取当前用户
onMounted(async ()=>{
  //判断是否断开连接
  currentUser.value = await userStoreAPI.getCurrentUser();
  onIsConnect(currentUser.value.id);
  chatData.value = await chatStoreAPI.getChatData();
  console.log("jsonchatData",JSON.stringify(chatData.value));

  if (0 == chatData.value.type){//表示群聊

      //映射出id->user的Map信息(排除掉当前用户)
      userIdMapUser.value =  chatData.value.userList.reduce((acc, item) => {
        // if (!acc[item.id]) {
        //   acc[item.id] = {};
        // }
        if (item.id != currentUser.value.id){//(排除掉当前用户)
          acc[item.id] = item;
        }
        return acc;
      }, {});
      console.log("userIdMapUser",userIdMapUser.value);

      const res = await getChatTeamMessageByTeamId(chatData.value.id);
      if (200 == res.code){
        msgData.value = res.data;
      }else {
        showToast('异常');
      }

  }else if (1 == chatData.value.type){//私聊
    //获取私聊的好友信息
    userIdMapUser.value =  chatData.value.userList.reduce((acc, item) => {
      if (!acc[item.id]) {
        acc[item.id] = {};
      }
      if (item.id != currentUser.value.id){//(排除掉当前用户)
        acc[item.id] = item;
        friendUser.value = item;
      }
      return acc;
    }, {});
    console.log("userIdMapUser",userIdMapUser.value);

    const res = await getChatFriendMessageByKey(chatData.value.friendKey);
    if (200 == res.code){
      msgData.value = res.data;
      console.log("msgData好友",msgData.value);
    }else {
      showToast('异常');
    }
  }

});


//加入队伍
const addTeam = async ()=>{
  //todo 加入队伍的逻辑
  showAddTeamDialog.value = false;//隐藏
  //请求加入队伍
  const res = await joinTeamInvite(chatTeamAddNet.value.teamId);
  if (200 == res.code){
    showToast('加入成功');
  }else {
    showToast(res.data.message);
  }
}

// 显示弹出框 邀请加入队伍
const showInviteTeamDialogMethod = (item:any) => {
  chatTeamAddNet.value = item;
  showAddTeamDialog.value = true;
}



</script>

<style scoped>
.sendIcon {
  transition: transform 0.2s ease-in-out;
}


@media (max-width: 768px) {  /* 针对较小屏幕，例如手机 */
  .infinite-list {
    height: 85vh;/* 好像这个80vh就是占比，无论屏幕多大都会占用90？ */
    padding: 0;
    margin-left: 3px;
    margin-right: 10px;
    list-style: none;
    position: fixed;
    width: 98%;
  }
}

@media (min-width: 769px) and (max-width: 1024px) {  /* 针对中等屏幕，例如平板电脑 */
  .infinite-list {
    height: 85vh;/* 好像这个80vh就是占比，无论屏幕多大都会占用90？ */
    padding: 0;
    margin-left: 3px;
    margin-right: 10px;
    list-style: none;
    position: fixed;
    width: 98%;
  }
}

@media (min-width: 1025px) {  /* 针对大屏幕，例如桌面电脑 */
  .infinite-list {
    height: 85vh;/* 好像这个80vh就是占比，无论屏幕多大都会占用90？ */
    padding: 0;
    margin-left: 3px;
    margin-right: 10px;
    list-style: none;
    position: fixed;
    width: 98%;
  }
}



.infinite-list .infinite-list-item-other {
  display: flex;
  /*align-items: center;*/
  justify-content: flex-start;
  height: 40px;
  background: var(--el-color-primary-light-9);
  margin: 5px;
  /*color: var(--el-color-primary);*/
}

.infinite-list .infinite-list-item-other + .list-item {
  margin-top: 5px;
}

.infinite-list .infinite-list-item-me {
  display: flex;
  /*align-items: center;*/
  justify-content: flex-end;
  height: 40px;
  background: var(--el-color-primary-light-9);
  margin: 5px;
}
.infinite-list .infinite-list-item-me + .list-item {
  margin-top: 5px;
}

.chatInputDiv{
  height: 8vh;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  /* 固定到底部bottom + position */
  position: fixed;
  bottom: 0;
}


</style>